import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Table, Tabs, Icon, Calendar, Spin, Input, Form} from 'antd';
import {TABLE, PAGE, FORM_OPTIONS} from '../constants';
import {conventEnumValueToString} from '../utils';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {hasPermissions, renderBoolean, exportDownload} from './utils';
import {PERMISSION} from './constants';
import {agentKind, priceClause, palletizing, currency, invoiceTemplateType} from '../Enum';
import routes from './routes';
import {getDetail, exportParts} from './api';
import moment from 'moment';
import styles from './style.css';
import max from 'lodash/max';
import min from 'lodash/min';
import Export from '../common/Export';

const {Search} = Input;
const FormItem = Form.Item;
const {Description} = DescriptionList;
const TabPanel = Tabs.TabPane;

class CustomCalendar extends React.PureComponent {
    dateCellRender = value =>
        this.props.calendar.some(
            d =>
                d.year === value.year() &&
          d.month - 1 === value.month() &&
          d.day === value.date()
        ) && <Icon type="check" />;
  
    render() {
        const calendar = this.props.calendar;
        let validRange = [];
        if(calendar.length > 0) {
            const years = calendar.map(d => d.year);
            const currentYear = moment().year();
            const currentMonth = moment().month() + 1;
            years.push(currentYear);
  
            const minYear = min(years);
            const maxYear = max(years);
            const minYearMonths = calendar
                .filter(d => d.year === minYear)
                .map(d => d.month);
            const maxYearMonths = calendar
                .filter(d => d.year === maxYear)
                .map(d => d.month);
            if(currentYear === minYear) minYearMonths.push(currentMonth);
            if(currentYear === maxYear) maxYearMonths.push(currentMonth);
            const minMonth = min(minYearMonths);
            const maxMonth = max(maxYearMonths);
            validRange[0] = moment([minYear, minMonth - 1]).startOf('month');
            validRange[1] = moment([maxYear, maxMonth - 1]).endOf('month');
        } else validRange = [moment().startOf('month'), moment().endOf('month')];
  
        return (
            <Calendar validRange={validRange} dateCellRender={this.dateCellRender} />
        );
    }
}
  
const EMPTY_ARRAY = [];

CustomCalendar.propTypes = {
    calendar: PropTypes.array
};

CustomCalendar.defaultProps = {
    calendar: EMPTY_ARRAY
};

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
        detailPagination: {
            pageIndex: PAGE.index,
            pageSize: 10,
            sortedColumnKey: 'code',
            sortedOrder: true,
        },
        searchPartCode: '',
        newParts: [],
        isSearch: false
    };
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    onClickExport = () => {
        this.setState({loading: true});
        exportParts(this.state.data.id).then(res => {
            this.setState({
                loading: false
            });
            exportDownload(res);
        });
    }
    onChangeDetail = (pagination, filters, sorter) => {
        this.setState({
            detailPagination: {
                pageIndex: pagination.current - 1,
                pageSize: pagination.pageSize,
                sortedColumnKey: sorter.columnKey,
                sortedOrder: sorter.order,
            }
        });
    };
    onSearchClaim = value => {
        const {parts} = this.state.data;
        this.setState({
            newParts: parts.filter(v => v.partCode.includes(value)),
            isSearch: true
        });
    }
    onChangeCodeValue = e => {
        this.setState({
            searchPartCode: e.target.value
        });
        if(!e.target.value)
            this.setState({
                isSearch: false,
                newDetails: []
            });
    }
    render() {
        const detailData = this.state.data || {};
        const detailPagination = this.state.detailPagination;
        const dealerParts = this.state.data.dealerParts || [];
        const dealerBanks = this.state.data.dealerBanks || [];
        const parts = this.state.data.parts || [];
        const isSearch = this.state.isSearch;
        const newParts = this.state.newParts;
        const orderingCalendars = this.state.data.orderingCalendars || [];

        const dealerPartsColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                render: (text, record) => `(${record.brandCode}) ${record.brandName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.tradeMethodCode',
                    defaultMessage: '贸易方式'
                }),
                dataIndex: 'tradeMethodCode',
                render: (text, record) => `(${record.tradeMethodCode}) ${record.tradeMethodName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.arrivedDealerCode',
                    defaultMessage: '送达方'
                }),
                dataIndex: 'arrivedDealerCode',
                render: (text, record) => `(${record.arrivedDealerCode}) ${record.arrivedDealerName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.priceClause',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'priceClause',
                render: text => conventEnumValueToString(priceClause, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.isSeparate',
                    defaultMessage: '商检分开打包'
                }),
                dataIndex: 'isSeparate',
                render: text => renderBoolean(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.isPlaned',
                    defaultMessage: '是否计划需求上报'
                }),
                dataIndex: 'isPlaned',
                render: text => renderBoolean(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.planedStartDate',
                    defaultMessage: '计划需求开始日'
                }),
                dataIndex: 'planedStartDate',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.planedEndDate',
                    defaultMessage: '计划需求结束日'
                }),
                dataIndex: 'planedEndDate',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.currency',
                    defaultMessage: '结算币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.mgmtRate',
                    defaultMessage: '备件管理费率'
                }),
                dataIndex: 'mgmtRate',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.labelRequirement',
                    defaultMessage: '标签要求'
                }),
                dataIndex: 'labelRequirement',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.palletizing',
                    defaultMessage: '托盘要求'
                }),
                dataIndex: 'palletizing',
                render: text => conventEnumValueToString(palletizing, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.shippingMark',
                    defaultMessage: '唛头'
                }),
                dataIndex: 'shippingMark',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.isClaim',
                    defaultMessage: '是否索赔判定'
                }),
                dataIndex: 'isClaim',
                render: text => renderBoolean(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.remark',
                    defaultMessage: '包装要求备注'
                }),
                dataIndex: 'remark',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.invoiceTemplateType',
                    defaultMessage: '发票模板类型'
                }),
                dataIndex: 'invoiceTemplateType',
                render: text => conventEnumValueToString(invoiceTemplateType, text)
            },
        ];

        const dealerBankColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.bankCode',
                    defaultMessage: '编号'
                }),
                dataIndex: 'bankCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.bankName',
                    defaultMessage: '名称'
                }),
                dataIndex: 'bankName',
            },
        ];

        const partsColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.partCode',
                    defaultMessage: '编号'
                }),
                dataIndex: 'partCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.colums.partName',
                    defaultMessage: '名称'
                }),
                dataIndex: 'partName',
            },
        ];

        const {options} = detailData;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        return (
            <div className={styles.detail}>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{
                            formatMessage({
                                id: 'detailPage.card.tradeMethodmessage',
                                defaultMessage: '基本信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPage.data.code',
                                defaultMessage: '编号',
                            })}>{detailData.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.name',
                                defaultMessage: '名称'
                            })}>{detailData.name}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.shortCode',
                                defaultMessage: '简码',
                            })}>{detailData.shortCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.shortName',
                                defaultMessage: '简称'
                            })}>{detailData.shortName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.kind',
                                defaultMessage: '客户分类',
                            })}>{conventEnumValueToString(agentKind, detailData.kind)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.country',
                                defaultMessage: '国家'
                            })}>{detailData.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.province',
                                defaultMessage: '省份',
                            })}>{detailData.province}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.city',
                                defaultMessage: '城市'
                            })}>{detailData.city}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.contactNumber',
                                defaultMessage: '联系电话'
                            })}>{detailData.contactNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.fax',
                                defaultMessage: '传真'
                            })}>{detailData.fax}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.address',
                                defaultMessage: '联系地址'
                            })}>{detailData.address}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.zipCode',
                                defaultMessage: '邮政编码'
                            })}>{detailData.zipCode}</Description>
                        </DescriptionList>
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detailPage.dealerPartInformation.title',
                            defaultMessage: '备件经营权限清单'
                        })}
                        bordered={false}>
                        <Table className="white-space-nowrap" rowKey="id"
                            columns={dealerPartsColumns} pagination={false} dataSource={dealerParts} {...TABLE} />
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detailPage.bank.title',
                            defaultMessage: '开户银行清单'
                        })}
                        bordered={false}>
                        <Table className="white-space-nowrap" rowKey="bankId"
                            columns={dealerBankColumns} pagination={false} dataSource={dealerBanks} {...TABLE} />
                    </Card>
                    <Card
                        title={<Row>
                            <Col span={4}>
                                {this.props.intl.formatMessage({
                                    id: 'detailPage.dealerParts.title',
                                    defaultMessage: '总代可提报备件清单'
                                })}
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={this.props.intl.formatMessage({
                                    id: 'detailPage.form.searchPartCode',
                                    defaultMessage: '备件号'
                                })}
                                {...FORM_OPTIONS.item}>
                                    <Search
                                        onSearch={this.onSearchClaim}
                                        value={this.state.searchPartCode}
                                        allowClear
                                        onChange={this.onChangeCodeValue}
                                        className={styles.minScreenSearchWidth}/>
                                </FormItem>
                            </Col>
                        </Row>}
                        bordered={false}
                        extra={<Export key="export" size="small" title={formatMessage({
                            id: 'newPanel.operation.exportDetail',
                            defaultMessage: '导出清单'
                        })} exportRequest={this.onClickExport} />}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="partId"
                            columns={partsColumns}
                            pagination={detailPagination}
                            dataSource={isSearch ? newParts : parts}
                            onChange={this.onChangeDetail}
                            loading={this.state.loading}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'detailPage.orderingCalendar.title',
                            defaultMessage: '订货日历详情'
                        })}
                        bordered={false}>
                        <Tabs type="card">
                            {orderingCalendars.map(item => (
                                <TabPanel
                                    key={item.partSaleOrderTypeId}
                                    tab={item.partSaleOrderTypeName}
                                    className={styles.calendar}>
                                    <CustomCalendar calendar={item.calendar} />
                                </TabPanel>
                            ))}
                        </Tabs>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPage.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import {injectIntl} from './intl';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
